package com.wmh.baseservice.robot.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.service.AdRoleService;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.utils.ServletUtils;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.robot.entity.RobotTaskStatement;
import com.wmh.baseservice.robot.enums.TaskStatus;
import com.wmh.baseservice.robot.pojo.dto.TaskStatementFileReps;
import com.wmh.baseservice.robot.pojo.vo.TaskStatementPageReqVO;
import com.wmh.baseservice.robot.service.RobotTaskStatementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

/**
 * @author 谢骏
 * @date 2023/3/17 14:11
 **/
@Api(tags = "自动化机器-任务报表相关接口", value="任务报表相关接口")
@RestController
@RequestMapping("robot/statement")
@Valid
public class RobotTaskStatementController {

    @Resource
    private AdRoleService adRoleService;

    @Resource
    private RobotTaskStatementService robotTaskStatementService;

    @Resource
    private UserUtil userUtil;


    @ApiOperation("任务报表分页")
    @PostMapping("page")
    @RequiresPermissions("robot.taskStatement.select")
    public String page(@Validated TaskStatementPageReqVO reqVO) {
        Long adId = userUtil.getId();
        boolean isLookMe = Objects.nonNull(reqVO.getLookMe()) && reqVO.getLookMe();
        boolean hasSupperAdmin = adRoleService.isHasSupperAdmin(adId);
        PageResult<RobotTaskStatement> pageResult = new PageUtil<RobotTaskStatement>(reqVO).startPage((page, wrapper) -> {
            wrapper.eq(!hasSupperAdmin || isLookMe, RobotTaskStatement.COL_AD_ID, adId);
            wrapper.eq(Objects.nonNull(reqVO.getTaskStatus()) && Arrays.stream(TaskStatus.ARRAYS).anyMatch(t -> Objects.equals(reqVO.getTaskStatus(), t)),
                    RobotTaskStatement.COL_TASK_STATUS, reqVO.getTaskStatus());
            wrapper.eqIfPresent(RobotTaskStatement.COL_ID, reqVO.getStatementId());
            wrapper.eqIfPresent(RobotTaskStatement.COL_AD_ID, reqVO.getAdId());
            wrapper.eqIfPresent(RobotTaskStatement.COL_TASK_ID, reqVO.getTaskId());
            wrapper.eqIfPresent(RobotTaskStatement.COL_TASK_TEMPLATE_ID, reqVO.getTaskTemplateId());
            wrapper.eqIfPresent(RobotTaskStatement.COL_ROBOT_NUMBER, reqVO.getRobotNumber());
            wrapper.likeIfPresent(RobotTaskStatement.COL_TASK_NAME, reqVO.getTaskName());
            wrapper.noSelect(RobotTaskStatement.class, RobotTaskStatement.COL_TASK_FILE_BASE64, RobotTaskStatement.COL_TASK_LOG_BASE64);
            wrapper.orderByDesc(RobotTaskStatement.COL_CREATE_TIME);
            robotTaskStatementService.page(page, wrapper);
        });
        return success(pageResult);
    }

    @ApiOperation(value = "删除任务报表")
    @PostMapping("delete")
    @RequiresPermissions("robot.taskStatement.delete")
    public String delete(
            @Size(min = 3, message = "删除失败,您没有提交报表信息")
            @NotBlank(message = "删除失败,您没有提交报表信息")
                             String statementIds) {
        List<Long> ids = JSON.parseArray(statementIds, Long.class);
        Long adId = userUtil.getId();
        boolean hasSupperAdmin = adRoleService.isHasSupperAdmin(adId);
        if (!robotTaskStatementService.remove(new QueryWrapper<RobotTaskStatement>()
                .in(RobotTaskStatement.COL_ID, ids)
                .eq(!hasSupperAdmin, RobotTaskStatement.COL_AD_ID, adId))) {
            throw new ServiceException("删除失败");
        }
        return success();
    }

    @ApiOperation(value = "下载任务报表附件")
    @PostMapping("dwFile")
    @RequiresPermissions("robot.taskStatement.dwFile")
    public void dwFile(Long statementId, HttpServletResponse response) throws IOException {
        // 获取文件响应对象
        TaskStatementFileReps taskStatementFile = robotTaskStatementService.getTaskStatementFile(statementId);
        // 输出
        ServletUtils.writeAttachment(response, taskStatementFile.getFileFullName(), taskStatementFile.getContent());
    }

    @ApiOperation(value = "下载任务日志附件")
    @PostMapping("dwLog")
    @RequiresPermissions("robot.taskStatement.dwLog")
    public void dwLog(Long statementId, HttpServletResponse response) throws IOException {
        // 获取文件响应对象
        TaskStatementFileReps taskStatementFile = robotTaskStatementService.getTaskStatementLog(statementId);
        // 输出
        ServletUtils.writeAttachment(response, taskStatementFile.getFileFullName(), taskStatementFile.getContent());
    }


}
